package cn.uniquesoft.controller.base;

import java.util.HashMap;
import java.util.List;

import cn.uniquesoft.manager.ClientManager;
import cn.uniquesoft.service.IRoleService;
import cn.uniquesoft.vo.AjaxResult;
import cn.uniquesoft.util.IpUtil;
import cn.uniquesoft.vo.RoleVO;
import cn.uniquesoft.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.uniquesoft.service.base.IBaseService;
import cn.uniquesoft.vo.page.DataGrid;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @创建人名 zjn
 * @创建日期 2017年8月29日 下午3:13:20
 * @文件描述 控制器基类
 */
public class BaseController<T> {
    @Autowired
    private IRoleService roleService;
    protected IBaseService<T> baseService;
    // 视图名称
    public String viewName = "";
    // 视图目录
    public String viewPath = "";

    // 跳转到首页
    @RequestMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request) {
        try {
            UserVO userVO = ClientManager.getInstance().getClient().getUser();
            HashMap<String, Object> model = new HashMap<String, Object>();
            if (null != userVO) {
                model.put("user", userVO);

                RoleVO role = new RoleVO();
                role.setCrolename(userVO.getCroleeng());
                role = this.roleService.findOne(role);
                model.put("role", role);
                return new ModelAndView(this.viewPath + "/index", model);
            } else {
                return new ModelAndView("/mgr/login/index");
            }
        } catch (Exception e) {
            return new ModelAndView("/mgr/login/index");
        }
    }

    // 跳转到添加或修改界面
    @RequestMapping(value = "/editPage")
    public ModelAndView editPage(int iid, String type,HttpServletRequest request) {
        try {
            UserVO userVO = ClientManager.getInstance().getClient().getUser();
            HashMap<String, Object> model = new HashMap<String, Object>();
            if (null != userVO) {
                model.put("user", userVO);

                RoleVO role = new RoleVO();
                role.setCrolename(userVO.getCroleeng());
                role = this.roleService.findOne(role);
                model.put("role", role);
                T item = null;
                if (iid != 0) {
                    item = this.baseService.findOneById(iid);
                    model.put("item", item);
                } else {
                    model.put("item", new Object());
                }

                model.put("type", type);
                return new ModelAndView(this.viewPath+ "/" + type, model);
            } else {
                return new ModelAndView("/mgr/login/index");
            }
        } catch (Exception e) {
            return new ModelAndView("/mgr/login/index");
        }
    }

    // 添加数据
    @RequestMapping(value = "/addItem", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult addItem(T item) {
//		ModelAndView result = new ModelAndView(this.viewPath+"index");
        AjaxResult ajaxResult = new AjaxResult();
        try {
            int count = this.baseService.save(item);
            if (count > 0) {
                ajaxResult.setRetcode(1);
                ajaxResult.setRetmsg("操作成功！");
            } else {
                ajaxResult.setRetcode(0);
                ajaxResult.setRetmsg("操作失败！");
            }
        } catch (Exception e) {
            ajaxResult.setRetcode(0);
            ajaxResult.setRetmsg("操作失败！");
        }
        return ajaxResult;
    }

    // 修改数据
    @RequestMapping(value = "/editItem", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult editItem(T item) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            int count = this.baseService.edit(item);
            if (count > 0) {
                ajaxResult.setRetcode(1);
                ajaxResult.setRetmsg("操作成功！");
            } else {
                ajaxResult.setRetcode(0);
                ajaxResult.setRetmsg("操作失败！");
            }
        } catch (Exception e) {
            ajaxResult.setRetcode(0);
            ajaxResult.setRetmsg("操作失败！");
        }
        return ajaxResult;
    }

    //删除数据
    @RequestMapping(value = "/delItem")
    @ResponseBody
    public AjaxResult deleteItem(String ids) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            int count = this.baseService.removeByIds(ids);
            if (count > 0) {
                ajaxResult.setRetcode(1);
                ajaxResult.setRetmsg("操作成功！");
            } else {
                ajaxResult.setRetcode(0);
                ajaxResult.setRetmsg("操作失败！");
            }
        } catch (Exception e) {
            ajaxResult.setRetcode(0);
            ajaxResult.setRetmsg("操作失败！");
        }
        return ajaxResult;
    }

    // 查找指定数据集合
    @RequestMapping(value = "/findOneByVO")
    @ResponseBody
    public T findOneByVO(T item) {
        return this.baseService.findOne(item);
    }

    // 查找指定数据集合
    @RequestMapping(value = "/findItems")
    @ResponseBody
    public List<T> findItems(T item) {
        return this.baseService.findList(item);
    }

    // 分页查询带总条数
    @RequestMapping(value = "/pageQuery", method = RequestMethod.GET)
    @ResponseBody
    public DataGrid queryPage(T item) {
        return this.baseService.queryPage(item);
    }

    // 分页查询不带总条数
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    @ResponseBody
    public List<T> query(T item) {
        return this.baseService.query(item);
    }

    /**
     * 日志
     */
    public static Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 失败返回
     *
     * @param retmsg
     * @return
     */
    public AjaxResult returnFailed(String retmsg) {
        return new AjaxResult(retmsg);
    }

    /**
     * 得到request对象
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }


    /** 公共异常处理 **//*
    @ExceptionHandler({ Exception.class })
	public Object exceptionHandler(Exception e, HttpServletRequest request) {
		ParamData params = new ParamData();
		logger.info("");
		StringBuilder sb = new StringBuilder(params.getString("loginIp")).append(request.getRequestURI()).append("请求发生异常:")
				.append(request.getServletPath()).append(":").append(params);
		logger.error(sb.toString(), e);
		return "common/500";
	}*/

	/*public void logBefore(String desc) {
		HttpServletRequest request = getRequest();
		logger.error("");
		StringBuilder sb = new StringBuilder(IpUtil.getIpAdd(request)).append(desc).append(":").append(request.getServletPath());
		logger.error(sb.toString());
	}*/
}
